package com.example.usercenter.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.usercenter.mapper.UserMapper;
import com.example.usercenter.model.domain.User;
import com.example.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private UserMapper userMapper;
    //重点用户
    private List<Long> mainUserList = Arrays.asList(5L);

    @Resource
    private RedissonClient redissonClient;

    //每天执行，预热推荐用户
    @Scheduled(cron = "0 30 11 * * *")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("spk:precachejob:docache:lock");



        try {
            //只有一个线程能够获取到锁
            //redis看门狗 监听当前线程，自动为key续期， 默认每次续期30s
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("getLock: " + Thread.currentThread().getId());
                Thread.sleep(300000);
                for (Long userId : mainUserList) {
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("spk:user:recommend:%s", userId);
                    ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.info("redis set key error");
                    }
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }

//    医院管理挂号平台	2019-01~2019-10
//    技术栈：SpringBoot+SpringCloud Alibaba+Spring+MyBatis-Plus
//    项目简介：医院预约挂号平台为患者提供在线上挂号的功能，用户提供手机号或者微信扫码登录，实名认证后可以选择时间为自己或者家人进行挂号；
//            使用SpringCloud+Nacos实现项目微服务化，划分项目为公共，用户，医院等服务，提高项目的可扩展性和容错性；
//            使用SpringCloud Gateway网关实现

}
